import { useEffect, useRef, type ChangeEvent } from 'react'
import type { PagePaperProps } from '../../CardPageType'
import './PagePaperStyle.sass'

function PagePaper (props: PagePaperProps) {
  // console.log(props.list)
  // #region 变量声明
  const optionText = ['A', 'B', 'C', 'D']
  const mainRef = useRef<HTMLDivElement | null>(null)
  // #endregion

  // #region 函数
  const onChange = (e: ChangeEvent<HTMLInputElement>, index: number) => {
    // console.log(mainRef.current?.children)
    if (props.state.isFinished) return
    const newList = [...props.state.list]
    newList[index].myResult = e.target.value
    props.dispatch({ type: 'list', value: newList })
  }
  // #endregion

  // #region Hooks
  useEffect(() => {
    // console.log('改变下标', props.state.curClickIndex)
    if (props.state.curClickIndex > -1 && mainRef.current) {
      document.documentElement.scrollTop = (mainRef.current.children[props.state.curClickIndex] as HTMLDivElement).offsetTop
    }
  }, [props.state.curClickIndex])
  // #endregion

  return (
    <>
      <div className="page_paper">
        <header>
          <span>单选题</span>
          <span>共{ props.state.list.length }题, 共计{ props.state.list.reduce((res, item) => res + item.score , 0) }分</span>
        </header>
        <main ref={ mainRef }>
          {
            props.state.list.map((item, index) => (
              <div className="item" key={ index }>
                <div className="no"><span>{ index + 1 }</span></div>
                <div className="title">
                  ( { item.score }分 )&nbsp;&nbsp;
                  { item.question }
                </div>
                <div className="options">
                  {
                    item.options.map((v, i) => (
                      <div key={ v } className="option">
                        <input disabled={ props.state.isFinished } type="radio" name={ index + '' } onChange={ (e) => onChange(e, index) } value={ optionText[i] } />
                        { optionText[i] + '. ' + v }
                      </div>
                    ))
                  }
                </div>
              </div>
            ))
          }
        </main>
      </div>
    </>
  )
}

export default PagePaper

